package com.eastseeway.radioproject.work;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.Data;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.eastseeway.radioproject.base.Const;
import com.eastseeway.radioproject.entities.VersionBean;
import com.eastseeway.radioproject.retrofit.RetrofitClient;
import com.eastseeway.radioproject.unlock.UnlockActivity;
import com.eastseeway.radioproject.utils.CRC16Check;
import com.eastseeway.radioproject.utils.SaveHelper;
import com.eastseeway.radioproject.utils.TimeUtils;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Files;

import okhttp3.ResponseBody;
import retrofit2.Response;

public class FirmwareUpgradeWork extends Worker {
    public FirmwareUpgradeWork(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        VersionBean versionInfo = new Gson().fromJson(getInputData().getString("version_info"), VersionBean.class);
        Log.e("12121", "remoteFileName: " + versionInfo.getSoftFile());
        String localSavedFirmwarePath = "";
        try {
//        http开头说明需要从服务器下载
            if (versionInfo.getSoftFile().startsWith("http")) {
//        从路径中获取文件名
                String fileName = versionInfo.getSoftFile().substring(versionInfo.getSoftFile().lastIndexOf('/') + 1);
                Log.e("12121","fileName:"+fileName);
                localSavedFirmwarePath = SaveHelper.getSaveFirmwarePath(fileName);
                versionInfo.setSoftFile(localSavedFirmwarePath);
                Log.e("12121","localSavedFirmwarePath:"+localSavedFirmwarePath);
                File file = new File(localSavedFirmwarePath);
                Files.deleteIfExists(file.toPath());
//            if (file.exists()) file.delete();
//            下载文件并保存在本地
                Response<ResponseBody> execute = RetrofitClient.getInstance().getServiceApi().downloadFirmware(fileName).execute();
                InputStream is = execute.body().byteStream();
                FileOutputStream fos = new FileOutputStream(localSavedFirmwarePath);
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }
                fos.close();
                is.close();
            }

            if (localSavedFirmwarePath.contains(".apk")) {
                versionInfo.setAddress(Const.ADDRESS_LOCALHOST);
                versionInfo.setUpdateTime(TimeUtils.getCurrentTime(TimeUtils.FORMAT_DATE_TIME_FULL1));
//                RadioApplication.getInstance().getJwsManager().jwsSilentInstallApp(saveFirmwarePath, true);
//                if (file.exists()) file.delete();
            } else {
//                硬件端的文件需要进行64字节对齐
                CRC16Check.alignFile(localSavedFirmwarePath);
                switch (versionInfo.getSoftStyle()) {
                    case "android":
                        versionInfo.setAddress(Const.ADDRESS_LOCALHOST);
                        break;
                    case "pressure_board":
                        versionInfo.setAddress(Const.ADDRESS_FROM_NEGATIVE_PRESSURE_BOARD);
                        break;
                    case "bottom_board":
                        versionInfo.setAddress(Const.ADDRESS_FROM_BOTTOM_BOARD);
                        break;
                    case "handle1":
                        versionInfo.setAddress(Const.ADDRESS_FROM_HANDLE_1_DATA_1);
                        break;
                    case "handle2":
                        versionInfo.setAddress(Const.ADDRESS_FROM_HANDLE_2_DATA_1);
                        break;
                    case "energy_board":
                        versionInfo.setAddress(Const.ADDRESS_FROM_ENERGY_BOARD);
                        break;
                    case "switch_board":
                        versionInfo.setAddress(Const.ADDRESS_FROM_SWITCH_BOARD);
                        break;
                }
            }
            /**
             * {@link UnlockActivity#observeData()}中会观察到这个消息
             * 然后根据不同的地址，进行不同的操作
             */
            Log.e("12121", versionInfo.getSoftStyle() + "下载成功，通知外部 " + new Gson().toJson(versionInfo));
            Data outputData = new Data.Builder()
                    .putString("version_info", new Gson().toJson(versionInfo))
                    .build();
            return Result.success(outputData);
        } catch (Exception e) {
            return Result.failure();
        }
    }
}
